package com.hcc.flow.server.service.sys;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hcc.flow.server.common.constant.Constant;
import com.hcc.flow.server.common.enums.IfStatusType;
import com.hcc.flow.server.common.model.ApiResult;
import com.hcc.flow.server.common.utils.StringUtilsV2;
import com.hcc.flow.server.dao.sys.OrgDao;
import com.hcc.flow.server.dao.sys.UserDao;
import com.hcc.flow.server.model.common.LoginUser;
import com.hcc.flow.server.model.sys.Org;
import com.hcc.flow.server.utils.CheckIdUtil;
import com.hcc.flow.server.utils.UserUtil;
import com.hcc.flow.server.vo.sys.OrgOneVO;
import com.hcc.flow.server.vo.sys.OrgVO;
import com.hcc.flow.server.where.sys.OrgWhere;

@Service
public class OrgService {
	//private static final Logger log = LoggerFactory.getLogger("adminLogger");
	@Autowired
	private OrgDao orgDao;
	@Autowired
	private UserDao userDao;
	
	
	public PageInfo<OrgVO> findAllOrgs(OrgWhere ewhere) {
		
		PageHelper.startPage(ewhere.getOffset(), ewhere.getLimit());
		if (ewhere.getSqlOrder() == null || ewhere.getSqlOrder().isEmpty()) {
			ewhere.setSqlOrder("t.create_time desc ");
		}
		PageHelper.orderBy(ewhere.getSqlOrder());
		List<OrgVO> log = orgDao.OrgList(ewhere);
		PageInfo<OrgVO> result = new PageInfo<OrgVO>(log);
		return result;
	}
	
	public OrgOneVO getOne(String orgId,Long indexId) {
		OrgOneVO org;
		if(StringUtilsV2.isNotBlank(orgId)) {
			org = orgDao.getById(orgId);
		}else {
			org = orgDao.getByIndexId(indexId);
		}
		if(org != null){
			String parentId = org.getParentId();
			String parentName = org.getParentName();
			List<String> ids = new ArrayList<String>();
			List<String> names = new ArrayList<String>();
			while (!"0".equals(parentId)) {
				ids.add(parentId);
				names.add(parentName);
				OrgOneVO orgW = orgDao.getById(parentId);
				if(orgW != null){
					parentId = orgW.getParentId();
					parentName = orgW.getParentName();
				}
			}
			Collections.reverse(ids);
			Collections.reverse(names);
			org.setParentIds(ids);
			org.setParentNames(names);
			if(Constant.PLATFORM_ORG_ID.equals(orgId)) {
				if(StringUtilsV2.isBlank(org.getWebLoginLogo())){
					org.setWebLoginLogoAll(Constant.PLATFORM_WEB_LOGIN_LOGO);
				}
				if(StringUtilsV2.isBlank(org.getWebLogo())){
					org.setWebLogoAll(Constant.PLATFORM_WEB_LOGO);
				}
				if(StringUtilsV2.isBlank(org.getWebTitle())){
					org.setWebTitle(Constant.PLATFORM_WEB_TITLE);
				}
			}else {
				OrgOneVO topOrg = getOne(Constant.PLATFORM_ORG_ID,null);
				if(topOrg != null) {
					if(StringUtilsV2.isBlank(org.getWebLoginLogo())){
						org.setWebLoginLogoAll(topOrg.getWebLoginLogoAll());
					}
					if(StringUtilsV2.isBlank(org.getWebLogo())){
						org.setWebLogoAll(topOrg.getWebLogoAll());
					}
					if(StringUtilsV2.isBlank(org.getWebTitle())){
						org.setWebTitle(topOrg.getWebTitle());
					}
				}else {
					if(StringUtilsV2.isBlank(org.getWebLoginLogo())){
						org.setWebLoginLogoAll(Constant.PLATFORM_WEB_LOGIN_LOGO);
					}
					if(StringUtilsV2.isBlank(org.getWebLogo())){
						org.setWebLogoAll(Constant.PLATFORM_WEB_LOGO);
					}
					if(StringUtilsV2.isBlank(org.getWebTitle())){
						org.setWebTitle(Constant.PLATFORM_WEB_TITLE);
					}
				}
			}
		}
		return org;
	}
	
	public List<OrgVO> findAllListOrgs(OrgWhere ewhere) {
		PageHelper.startPage(-1, -1, false, null, false);
		if (ewhere.getSqlOrder() == null || ewhere.getSqlOrder().isEmpty()) {
			ewhere.setSqlOrder("t.create_time desc ");
		}
		List<OrgVO> log = orgDao.OrgList(ewhere);

		return log;
	}
	


	
	public ApiResult<?> save(Org org,boolean resource){
		ApiResult<?> apiResult = verifyForm(org,resource);// 校验数据
		if(apiResult != null){
			return apiResult;
		}
		LoginUser user = UserUtil.getLoginUser();
		//新增
		if(StringUtilsV2.isBlank(org.getOrgId())){
			/*if((StringUtilsV2.isBlank(org.getParentId()) || "0".equals(org.getParentId())) && !Constant.SYSTEM_MANAGE_TOP_USER_IDS.contains(user.getUserId())){
				return ApiResult.error("只有账号：admin才能新增顶级机构");
			}*/
			if(StringUtilsV2.isBlank(org.getParentId()) || "0".equals(org.getParentId())) {
				if(!Constant.SYSTEM_MANAGE_TOP_USER_IDS.contains(user.getUserId())) {
					if(userDao.getPermissionByPermAndUserId(user.getUserId(), "sys:org:addBrother") == 0){
						return ApiResult.error("您没有新增同级机构的权限");
					}
					org.setParentId(user.getParentOrgId());
				}
			}
			org.setCreateUserId(user.getUserId());
			org.setCreateOrgId(user.getOrgId());
			if(org.getCreateTime() == null){
				org.setCreateTime(new Date());
			}
			if(StringUtilsV2.isBlank(org.getResource())){
				org.setResource(IfStatusType.N.getCode());
			}
			orgDao.save(org);
		}else{//修改
			if(org.getOrgId().equals("1") && !"C".equals(org.getOrgStatus())){
				return ApiResult.error("系统机构不能改变机构状态");
			}
			ApiResult<?> checkAr = CheckIdUtil.checkId(Arrays.asList("1","2"), org.getOrgId());
			if(!checkAr.isSuccess()){
				return checkAr;
			}
			if(StringUtilsV2.isBlank(org.getResource())){
				Org localOrg = orgDao.getById(org.getOrgId());
				org.setResource(localOrg.getResource());
			}
			orgDao.update(org);
		}
		return ApiResult.ok();
	}


	/**
	 * 验证参数是否正确
	 */
	
	public ApiResult<?> verifyForm(Org org,boolean resource) {
		if (org == null) {
			return ApiResult.error("机构数据不能为空");
		}
		if (org.getOrgId() == null && CollectionUtils.isEmpty(org.getOrgTypeIds())) {
			return ApiResult.error("所属机构类型ID不能为空");
		}
		org.setOrgTypeId(StringUtilsV2.join(org.getOrgTypeIds(),","));
		if (StringUtilsV2.isBlank(org.getOrgName())) {
			return ApiResult.error("机构名称不能为空");
		}
		if (StringUtilsV2.isBlank(org.getOrgCode())){
			return ApiResult.error("机构编码不能为空");
		}
		Org localCodeOrg = orgDao.getByCode(org.getOrgCode());
		if(localCodeOrg != null && (StringUtilsV2.isBlank(org.getOrgId()) || !org.getOrgId().equals(localCodeOrg.getOrgId()))){
			return ApiResult.error("机构编码已存在，其对应机构："+localCodeOrg.getOrgName());
		}
		// 上级菜单id
		String parentId = org.getParentId();
		// 没传父菜单id默认为顶级菜单
		if (StringUtilsV2.isBlank(parentId) || "0".equals(parentId)) {
			org.setParentId("0");
			// 默认为顶级
			org.setLevel(1);
		} else {
			Org parentOrg = orgDao.getById(parentId);
			Integer parentLevel = parentOrg.getLevel();
			if (parentLevel != null) {
				org.setLevel(parentLevel + 1);
			}
		}
		if(StringUtilsV2.isNotBlank(org.getOrgId())){
			LoginUser loginUser = UserUtil.getLoginUser();
			if(resource){
				if(Constant.PLATFORM_ORG_ID.equals(org.getOrgId())){
					return ApiResult.error("该机构为系统顶级机构，不用分配资源（默认拥有全部资源）</br>请返回上一步直接点击'跳过资源分配并保存");
				}
				if(!Constant.SYSTEM_MANAGE_TOP_USER_IDS.contains(loginUser.getUserId()) && "0".equals(org.getParentId())){
					return ApiResult.error("该机构为顶级机构，只有账号:admin有资源分配权限</br>请返回上一步直接点击'跳过资源分配并保存");
				}
				if(org.getOrgId().equals(loginUser.getOrgId())){
					//return ApiResult.error("登录人不能自己对所属机构进行资源分配</br>请返回上一步直接跳过资源分配并保存");
					return ApiResult.error("不能对自己所属机构进行资源分配，</br>要想对当前机构进行资源分配，请联系你的上级机构"+(StringUtilsV2.isNotBlank(loginUser.getParentOrgName())?"("+loginUser.getParentOrgName()+")":"")+"管理员操作.</br>或者请返回上一步直接点击'跳过资源分配并保存'");
				}
			}
			Org oldOrg = orgDao.getById(org.getOrgId());
			if(oldOrg != null){
				if(org.getOrgId().equals(loginUser.getOrgId())){
					if(!org.getOrgTypeId().equals(oldOrg.getOrgTypeId())){
						return ApiResult.error("登录人不能对自己所属机构的机构类型进行变更，</br>要想变更，请联系你的上级机构"+(StringUtilsV2.isNotBlank(loginUser.getParentOrgName())?"("+loginUser.getParentOrgName()+")":"")+"管理员操作.");
					}
					if(!org.getOrgStatus().equals(oldOrg.getOrgStatus())){
						return ApiResult.error("登录人不能对自己所属机构的机构状态进行变更，</br>要想变更，请联系你的上级机构"+(StringUtilsV2.isNotBlank(loginUser.getParentOrgName())?"("+loginUser.getParentOrgName()+")":"")+"管理员操作.");
					}
				}
			}
		}
		return null;
	}
	
	

}
